<?php

class ProductPictureController extends Controller
{
	/**
	 * @var string 默认使用的布局文件。
	 * 默认值为 '//layouts/column2', 表示使用2栏布局。
	 * 布局文件的路径为 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * 显示指定的产品图片信息
	 * @param integer 要显示的产品图片id
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * 删除指定的产品图片
	 * 在AJAX模式，当删除成功后，数据表格会被刷新
	 * 而在普通模式则会跳转到管理页面
	 * @param integer 要删除的产品图片id
	 */
	public function actionDelete($id)
	{
		$model = $this->loadModel($id);

		if(Yii::app()->request->isAjaxRequest)
		{
			// 禁止jQuery 重复初始化
	        Yii::app()->clientScript->scriptMap['jquery.js'] = false;

			if(isset($_POST['action']) && $_POST['action'] == 'confirmDelete')
			{
				// 删除生成的3种尺寸的图片
				$dir=Yii::app()->basePath."/../uploads/product/";
				$file=$model->name.".".$model->ext;
				Util::deletePictures($dir, $file);

				// 删除模型
				$model->delete();

				echo CJSON::encode(array(
					'status' => 'success',
					'content' => '<div class="tips tips-ok">
				        <i class="ico-ok"></i>
				        <div class="cont">
				            <h4>Info</h4>
				            <p>Deleted succussfully.</p>
				        </div>
				    </div>',
				));
				exit;
			}
			else if(isset($_POST['action']))
			{
				echo CJSON::encode( array(
					'status' => 'canceled',
					'content' => '<div class="tips tips-info">
				        <i class="ico-info"></i>
				        <div class="cont">
				            <h4>Info</h4>
				            <p>Deleted canceled.</p>
				        </div>
				    </div>',
					));
				exit;
			}
			else
			{
				echo CJSON::encode( array(
					'status' => 'failure',
					'content' => $this->renderPartial('delete', array(
						'model' => $model ), true, true),
					));
				exit;
			}
		}
		else
		{
			if(isset($_POST['confirmDelete']))
			{
				// 删除生成的3种尺寸的图片
				$dir=Yii::app()->basePath."/../uploads/product/";
				$file=$model->name.".".$model->ext;
				Util::deletePictures($dir, $file);

				// 删除模型
				$model->delete();
				$this->redirect(array('admin'));
			}
			else if(isset($_POST['denyDelete']))
				$this->redirect(array('view','id' => $model->id));
			else
				$this->render('delete', array('model' => $model));
		}
	}

	/**
	 * 删除所有上传后没有绑定到指定产品的图片
	 */
	public function actionDeleteUnused()
	{
		$criteria = new CDbCriteria;
		$criteria->addCondition('product_id is null');

		// 找到符合条件的图片并删除之
		$models=ProductPicture::model()->findAll($criteria);
		foreach ($models as $model) {
			// 删除生成的3种尺寸的图片
			$dir=Yii::app()->basePath."/../uploads/product/";
			$file=$model->name.".".$model->ext;
			Util::deletePictures($dir, $file);
		}
		
		ProductPicture::model()->deleteAll($criteria);

		if(isset(Yii::app()->request->isAjaxRequest)) {
			echo CJSON::encode(array(
				'status' => 'success',
				'content' => '<div class="tips tips-ok">
			        <i class="ico-ok"></i>
			        <div class="cont">
			            <h4>Congratulations!</h4>
			            <p>Unused pictures successfully deleted.</p>
			        </div>
			    </div>'
			));
		} else
			$this->redirect(array('index'));
	}

	/**
	 * 管理产品图片
	 */
	public function actionIndex()
	{
		$model=new ProductPicture('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['ProductPicture']))
			$model->attributes=$_GET['ProductPicture'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=ProductPicture::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='product-picture-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	/**
	 * 以AJAX 方式上传图片
	 */
	public function actionUpload()
	{
		try{
			$model=new ProductPicture;

			// 取得上传的文件
			$picture_file = CUploadedFile::getInstanceByName('Filedata');

			if(!$picture_file || $picture_file->getHasError()){
				echo 'Error: Invalid document';
				Yii::app()->end();
			}

			// remember the post params?
			// $yourvar = Yii::app()->request->getParam('yourvarname');
			// $picture_name = $picture_file->name;

			// 生成一个随机的名称
			// @TODO: 需要判断名称是否重复
			$newName = Util::genRandomString(16);

			$model->name = $newName;
			$model->size = $picture_file->size;
			$model->ext = $picture_file->extensionName;

			if($model->save())
			{
				// 图片上传后，在session中记录其id，以用于创建或更新产品时绑定图片到产品
				$temp=Yii::app()->session['productPicture'];
				$temp[] = $model->id;
				Yii::app()->session['productPicture'] = $temp;

				$ext = $picture_file->extensionName;
				$path = Yii::app()->basePath.'/../uploads/product/'.$newName.'.'.$ext;

				// 原图上传后生成中图和小图
				if($picture_file->saveAs($path))
				{
					/*$im = null;
					$imagetype = strtolower($ext);
					if($imagetype == 'gif')
					    $im = imagecreatefromgif($path);
					else if ($imagetype == 'jpg')
					    $im = imagecreatefromjpeg($path);
					else if ($imagetype == 'png')
					    $im = imagecreatefrompng($path);

					// 创建中缩略图
					CThumb::resizeImage ( 
					$im,480, 360,
					Yii::app()->basePath.'/../uploads/product/medium/'.$newName.'.'.$ext, $ext);

					// 创建小缩略图
					CThumb::resizeImage ( 
					$im,160, 120,
					Yii::app()->basePath.'/../uploads/product/small/'.$newName.'.'.$ext, $ext);*/
					Util::genThumbnail('product', $newName, $ext);
					
				}

				// Return the file id to the script
				// This will display the thumbnail of the uploaded file to the view
				echo "FILEID:" . Yii::app()->getBaseUrl() .
					'/uploads/product/'.
					$newName.'.'.$ext;
			}
		}
		catch(Exception $e){
			echo 'Error: ' . $e->getMessage();
		}
		Yii::app()->end();

	}
}
